package mroute

import (
	"github.com/gin-gonic/gin"
	"go.mongodb.org/mongo-driver/bson"
	"mygo/mystruct"
	"mygo/mymongo"
	"path/filepath"
	"encoding/json"
	"mygo/global"
	"os"
	"fmt"
)


/* =================================================================================
   在线文档接口
*/
func MywordModel(cont *gin.Context) {
	queryid := cont.Query("_id")
   fileId := cont.DefaultQuery("id","")
   name := cont.Query("name")
   code := cont.Query("code")
   codb := mymongo.Get_Code(code)
   if codb == nil {
   	cont.JSON(mystruct.StatusOK, gin.H{"code": mystruct.MyCodeErr, "msg": "标识不存在"})
   	return	
   }
   file_Path := filepath.Join(global.Mtoken.Download_Path, codb.Body.Apiid, queryid, name, fileId + ".json")
   switch cont.Request.Method {
   	case "POST":
   		var requestData map[string]interface{}
    		cont.ShouldBindJSON(&requestData)
    		jsonBytes, err := json.MarshalIndent(requestData, "", "  ")
    		if err != nil {
    			cont.JSON(mystruct.StatusOK, gin.H{"code": mystruct.MyCodeErr, "msg": err.Error()})
    			return
    		}  
    		if err := os.WriteFile(file_Path, jsonBytes, 0777); err != nil {
				cont.JSON(mystruct.StatusOK, gin.H{"code": mystruct.MyCodeErr, "msg": err.Error()})
				return
			}
			cont.JSON(mystruct.StatusOK, gin.H{"code": mystruct.MyCodeOk, "msg": "保存完成"})

    	case "GET":
    		if fileId == "" {
    			export_file_Path := filepath.Join(global.Mtoken.Download_Path, codb.Body.Apiid, queryid, name, queryid + ".json")
    			if !mystruct.Exists(export_file_Path) {
    				cont.JSON(mystruct.StatusOK, gin.H{"code": mystruct.MyCodeErr, "msg": "文件不存在"})
    				return
    			}
    			cont.Header("Content-Type", "application/octet-stream")
				cont.Header("Content-Transfer-Encoding", "binary")
				cont.Header("Cache-Control", "no-cache")
				cont.Header("Content-Disposition", "attachment; filename=" + queryid + ".json")
				cont.Header("Content-Length", fmt.Sprintf("%d", mystruct.GetFileSize(export_file_Path)))
    			cont.File(export_file_Path)
    			return
    		}
    		ret := word_auth_data(cont, codb, queryid, name, fileId)
	    	if ret == nil {
	    		cont.Abort()
	    		return
	    	}
	    	var jsonContent interface{}
    		if mystruct.Exists(file_Path) {
				fileData, _ := os.ReadFile(file_Path)
				json.Unmarshal(fileData, &jsonContent);
			   cont.JSON(mystruct.StatusOK, gin.H{"code": mystruct.MyCodeOk, "msg": gin.H{"data": jsonContent, "model": ret}})
			}else{
				cont.JSON(mystruct.StatusOK, gin.H{"code": mystruct.MyCodeErr, "msg": gin.H{"data": jsonContent, "model": ret}})
			}

   }
}
func word_auth_data(cont *gin.Context, codb *mymongo.Curs, queryid string, name string, fileId string) bson.M {
	ret, res := mymongo.Wacth_One(queryid, codb)
	if ret.Code != 1 {
		cont.JSON(mystruct.StatusUnauthorized, gin.H{"error": "数据id不存在"})
		return nil
	}
	obj, ok := res["data"].(bson.M)[name]
	if (!ok) {
		cont.JSON(mystruct.StatusUnauthorized, gin.H{"error": "字段非文档对象"})
		return nil
	}
	objMap := obj.(bson.M)
	if objMap["id"].(string) != fileId {
		cont.JSON(mystruct.StatusUnauthorized, gin.H{"error": "文档id不存在"})
		return nil
	}
	dir := filepath.Join(global.Mtoken.Download_Path, codb.Body.Apiid, queryid, name)
	if !mystruct.Exists(dir) {
		os.MkdirAll(dir, os.ModePerm)
	}
	return res
}